/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.core.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;
import org.elsfs.cloud.common.core.jackson.deser.ZonedDateTimeDeserializer;
import org.elsfs.cloud.common.util.date.DatePattern;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.context.annotation.Bean;

/**
 * JacksonConfig
 *
 * @author zeng
 */
@AutoConfiguration
@ConditionalOnClass(ObjectMapper.class)
@AutoConfigureBefore(JacksonAutoConfiguration.class)
public class JacksonConfiguration {

  @Value("${spring.jackson.time-zone:GMT+8}")
  private TimeZone timeZone;

  @Bean
  @ConditionalOnMissingBean
  Jackson2ObjectMapperBuilderCustomizer customizer() {
    return builder -> {
      builder.serializerByType(Long.class, ToStringSerializer.instance);
      builder.modules(javaTimeModule());
    };
  }

  JavaTimeModule javaTimeModule() {
    JavaTimeModule module = new JavaTimeModule();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_MS_PATTERN);
    module.addDeserializer(
        ZonedDateTime.class, new ZonedDateTimeDeserializer(formatter, timeZone.toZoneId()));
    module.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer(formatter));
    return module;
  }
}
